<?php
/**
 * Created By virus_cms
 * Author: Virus
 * Date: 2020/3/23
 * Time: 22:54
 */

namespace app\admin\library\traits;


trait Backend
{
    /**
     * 查询所有数据
     * @param bool $field
     * @param array $order
     * @return mixed
     */
    public function getList($field = true, $order = ["id" => "asc"])
    {
        return $this->field($field)->order($order)->select();
    }

    /**
     * 添加数据
     * @param array $data
     * @return mixed
     */
    public function addData(array $data)
    {
        $data['create_time'] = time();

        return $this->insert($data, true);
    }

    /**
     * 根据id获取单个数据
     * @param int $id
     * @param bool $field
     * @return mixed
     */
    public function getOneDataById(int $id, $field = true)
    {
        $where = ['id' => $id];

        return $this->where($where)->field($field)->find()->getData();
    }

    /**
     * 根据特定条件查询单个数据
     * @param array $where
     * @param bool $field
     * @return mixed
     */
    public function getOneDataByWhere(array $where, $field = true)
    {
        return $this->where($where)->field($field)->find();
    }

    /**
     * 根据id进行更新数据
     * @param int $id
     * @param array $data
     * @return mixed
     */
    public function updateDataById(int $id, array $data)
    {
        return $this->where('id', $id)->update($data);
    }

    /**
     * 删除
     * @param int $id
     * @return mixed
     */
    public function deleteOneData(int $id)
    {
        return $this->where('id', $id)->delete();
    }

    /**
     * 批量删除
     * @param array $ids
     * @return string
     */
    public function batchDeleteData(array $ids)
    {
        try {
            foreach ($ids as $id) {
                return $this->where('id', $id)->delete();
            }
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }
}